package org.iteam.web.kaptcha.action;

import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.iteam.web.kaptcha.Producer;
import org.iteam.web.kaptcha.util.Config;
import org.iteam.web.kaptcha.util.KaptchaConfig;

import com.opensymphony.xwork2.ActionSupport;

public class KaptchaAction extends ActionSupport implements SessionAware,
		ServletRequestAware, ServletResponseAware {
	protected HttpServletRequest request;
	protected HttpServletResponse response;
	protected Map<String, Object> session;
	private String number;
	public void setServletResponse(HttpServletResponse response) {
		this.response = response;
	}

	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}

	public void setSession(Map<String, Object> session) {
		this.session = session;
	}

	/**
	 * 
	 */
	private static final long serialVersionUID = -2625880149271490442L;

	private Properties props = new Properties();

	private Producer kaptchaProducer = null;

	private String sessionKeyValue = null;

	private String sessionKeyDateValue = null;
	private static List<KaptchaConfig> config = new ArrayList<KaptchaConfig>();

	static {
		try {
			/*
			 * URL url =
			 * KaptchaAction.class.getResource("/KaptchaConfigxml.xml");
			 * System.out.println(url); String filePath = java.net.URLDecoder
			 * .decode(url.getPath(), "UTF-8");*
			 */

			Document document = null;
			SAXReader saxReader = new SAXReader();
			document = saxReader.read(KaptchaAction.class
					.getResourceAsStream("/KaptchaConfigxml.xml"));
			// document = saxReader.read(new File(filePath)); //
			// 读取XML文件,获得document对象
			Element root = document.getRootElement();
			@SuppressWarnings("unchecked")
			List<Element> list = root.elements();
			for (Element element : list) {
				config.add(new KaptchaConfig(element
						.elementTextTrim("param-name"), element
						.elementTextTrim("param-value")));
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void init(List<KaptchaConfig> conf) throws ServletException {

		// Switch off disk based caching.
		ImageIO.setUseCache(false);
		for (KaptchaConfig kaptchaConfig : conf) {
			this.props.put(kaptchaConfig.getName(), kaptchaConfig.getValue());
		}
		Config config = new Config(this.props);
		this.kaptchaProducer = config.getProducerImpl();
		this.sessionKeyValue = config.getSessionKey();
		this.sessionKeyDateValue = config.getSessionDate();
	}

	// @Action(value = "/Kaptcha", interceptorRefs = {
	// @InterceptorRef("defaultStack") })
	public void kaptcha() throws Exception {
		init(config);
		// Set to expire far in the past.
		response.setDateHeader("Expires", 0);
		// Set standard HTTP/1.1 no-cache headers.
		response.setHeader("Cache-Control",
				"no-store, no-cache, must-revalidate");
		// Set IE extended HTTP/1.1 no-cache headers (use addHeader).
		response.addHeader("Cache-Control", "post-check=0, pre-check=0");
		// Set standard HTTP/1.0 no-cache header.
		response.setHeader("Pragma", "no-cache");

		// return a jpeg
		response.setContentType("image/jpeg");

		// create the text for the image
		String capText = this.kaptchaProducer.createText();

		// store the text in the session
		session.put(this.sessionKeyValue, capText);

		// store the date in the session so that it can be compared
		// against to make sure someone hasn't taken too long to enter
		// their kaptcha
		session.put(this.sessionKeyDateValue, new Date());

		// create the image with the text
		BufferedImage bi = this.kaptchaProducer.createImage(capText);

		ServletOutputStream out = response.getOutputStream();

		// write the data out
		ImageIO.write(bi, "jpg", out);
	}

	public String getNumber() {
		return number;
	}

	public void setNumber(String number) {
		this.number = number;
	}
}
